package cn.fanqinghong.ymcc.utils;

import cn.fanqinghong.ymcc.domain.MessageEmail;
import cn.fanqinghong.ymcc.util.ApplicationContextUtils;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * FAN
 * 发送邮件
 * 2022/6/13  18:54
 */
public class MailUtil {

    private static JavaMailSender javaMailSender;

    /**
     * 发送审核通过的邮件
     * @param messageEmail
     */
    public static void sendEasyMailPass(MessageEmail messageEmail){
        try {
            javaMailSender = ApplicationContextUtils.getBean(JavaMailSender.class);

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            //3.发送激活邮件
            SimpleMailMessage message = new SimpleMailMessage();
            //发送人
            message.setFrom("1412644233@qq.com");
            //收件人
            message.setTo(messageEmail.getEmail());
            message.setSubject(messageEmail.getTitle());
            message.setText(messageEmail.getContent());
            javaMailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送复杂邮件
     */
    public static void sendMultipartMail(){
        try {
            javaMailSender = ApplicationContextUtils.getBean(JavaMailSender.class);
            //创建复杂邮件对象
            MimeMessage mimeMessage = MailUtil.javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1412644233@qq.com");
            helper.setSubject("邮件标题");
            //第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>新型冠状病毒防护守则</h1>"+
                    "<img src='http://img30.360buyimg.com/5db64acfE6ab2b09e/38b5cb3dc38b4b1f.jpg\"' />",true);
            //添加附件
            helper.addAttachment("文件名.jpg",new File("C:\\aa.jpg"));
            //收件人
            helper.setTo("1412644233@qq.com");
            //发送邮件
            MailUtil.javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
